/**
 * 临时数据管理路由
 *
 * Created by liuxuechao on 2022/07/31.
 */
const middleware = require('./../middleware');
const ephemeralData = require('../../models/ephemeral-data');
const PhoenixError = require('../../models/phoenix-error');

function storageEphemeralData(req, res, next) {
  (async () => {
    const { data } = req.body;
    const created = await ephemeralData.createEphemeralData(data);
    res.json(created);
  })().catch((err) => {
    next(new PhoenixError(err));
  });
}

function getEphemeralData(req, res, next) {
  (async () => {
    const { key } = req.query;
    const data = await ephemeralData.getEphemeralData(key);
    res.json(data);
  })().catch((err) => {
    next(new PhoenixError(err));
  });
}

module.exports = (app, prefix) => {
  const ephemeralDataURL = `${prefix}/ephemeral-data.json`;

  // 存储临时数据
  app.post(ephemeralDataURL, middleware.user.requireTokenUnexpired);
  app.post(ephemeralDataURL, middleware.user.requireAvailable);
  app.post(ephemeralDataURL, middleware.user.requireTester);
  app.post(ephemeralDataURL, storageEphemeralData);

  // 获取临时数据
  app.get(ephemeralDataURL, middleware.user.requireTokenUnexpired);
  app.get(ephemeralDataURL, middleware.user.requireAvailable);
  app.get(ephemeralDataURL, middleware.user.requireTester);
  app.get(ephemeralDataURL, getEphemeralData);
};
